let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');

let app = express();
// 处理跨域
let cors = require('cors')
app.use(cors())

// 1. 导入用于生成 JWT 字符串的包
const jwt = require("jsonwebtoken");
// 2. 导入用于将客户端发送过来的 JWT 字符串，解析还原成 JSON 对象的包
const expressJWT = require("express-jwt");
// 3. secret 一个密钥字符串
const secretKey = "stu-manager key";
// 挂载全局，方便其它Router中使用
app.locals.jwt = jwt;
app.locals.expressJWT = expressJWT;
app.locals.secretKey = secretKey;

// token验证中间件，如果请求中没有token信息，不通过。unless：白名单
app.use(expressJWT({secret: secretKey, algorithms: ['HS256']}).unless({path: ["/api/login.do", "/api/logout.do"]}));

app.use(logger('dev'));
// req.body可以接收json格式的参数
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//中间件，统一处理打印及分页插件，必须写在路由之前
const pager = require("./util/PagerHelper.js");
app.use((req, res, next) => {
  console.log("req.url:", req.url)
  console.log("req.body:", req.body);
  let {pageNum, pageSize} = req.query;
  if (pageNum && pageNum.trim().length > 0) {
    pager.pageNum = parseInt(pageNum);
  }
  if (pageSize && pageSize.trim().length > 0) {
    pager.pageSize = parseInt(pageSize);
  }
  // console.log("pager", pager);
  next();
});
let loginRoute = require('./routes/LoginRoute');
let dormAdminsRoute = require('./routes/DormAdminsRoute');
let studentsRoute = require('./routes/StudentsRoute');
let dormsRoute = require('./routes/DormsRoute');
let menusRoute = require('./routes/MenusRoute');
let absencesRoute = require('./routes/AbsencesRoute');

app.use('/api/', loginRoute);
app.use('/api/dormAdmins', dormAdminsRoute);
app.use('/api/students', studentsRoute);
app.use('/api/dorms', dormsRoute);
app.use('/api/menus', menusRoute);
app.use('/api/absences', absencesRoute);

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};
  //
  // // render the error page
  // res.status(err.status || 500);
  console.log(err);
  res.json(err);
});

let port = 8081;
app.listen(port, () => {
  console.log(`服务已启动：http://localhost:${port}`);
})

module.exports = app;
